let socket: WebSocket | null = null;
let currentUser: string | null = null;

interface WebSocketMessage {
  type: string;
  username?: string;
  message?: string;
  users?: string[];
}

// 页面加载时从localStorage获取上次登录的用户名
window.onload = function (): void {
  const savedUsername = localStorage.getItem('lastUsername');
  const usernameInput = document.getElementById('username') as HTMLInputElement;
  if (savedUsername && usernameInput) {
    usernameInput.value = savedUsername;
  }
  usernameInput?.focus();
};

function login(): void {
  const usernameInput = document.getElementById('username') as HTMLInputElement;
  const username = usernameInput?.value.trim();
  if (!username) {
    alert('请输入用户名');
    return;
  }

  currentUser = username;
  // 保存用户名到localStorage
  localStorage.setItem('lastUsername', username);
  socket = new WebSocket('ws://localhost:8080');

  socket.onopen = () => {
    document.getElementById('login').style.display = 'none';
    document.getElementById('chat').style.display = 'block';
    socket.send(JSON.stringify({
      type: 'login',
      username: currentUser
    }));
  };

  socket.onmessage = (event: MessageEvent) => {
    const data: WebSocketMessage = JSON.parse(event.data);

    if (data.type === 'message') {
      addMessage(data.username, data.message);
    } else if (data.type === 'userList') {
      updateUserList(data.users);
    } else if (data.type === 'userJoined') {
      addMessage('系统', `${data.username} 加入了聊天`);
    } else if (data.type === 'userLeft') {
      addMessage('系统', `${data.username} 离开了聊天`);
    } else if (data.type === 'error') {
      alert(data.message);
      document.getElementById('login').style.display = 'block';
      document.getElementById('chat').style.display = 'none';
    }
  };

  socket.onclose = () => {
    addMessage('系统', '您已断开连接');
    document.getElementById('login').style.display = 'block';
    document.getElementById('chat').style.display = 'none';
  };
}

function sendMessage(): void {
  const messageInput = document.getElementById('message') as HTMLInputElement;
  const message = messageInput?.value;
  if (message && socket) {
    socket.send(JSON.stringify({
      type: 'message',
      username: currentUser,
      message: message
    }));
    (document.getElementById('message') as HTMLInputElement).value = '';
    document.getElementById('message').blur();
  }
}

const usernameInput = document.getElementById('username') as HTMLInputElement;
usernameInput.addEventListener('keydown', (e: KeyboardEvent) => {
  if (e.key === 'Enter') {
    login();
  }
});
// 全局键盘事件监听
window.addEventListener('keydown', (e: KeyboardEvent) => {
  if (e.key === 'Enter' && document.getElementById('chat').style.display === 'block') {
    if (document.activeElement !== document.getElementById('message')) {
      document.getElementById('message').focus();
    } else {
      sendMessage();
      document.getElementById('message').blur();
    }
  }
});

const messageInput = document.getElementById('message') as HTMLInputElement;
messageInput.addEventListener('keydown', (e: KeyboardEvent) => {
  if (e.key === 'Enter') {
    sendMessage();
  }
});

function getUsernameColor(username: string): string {
  if (username === 'System') return '#ff9800';

  let hash = 0;
  for (let i = 0; i < username.length; i++) {
    hash = username.charCodeAt(i) + ((hash << 7) - hash);
  }
  return `hsl(${Math.abs(hash % 360)}, 85%, 65%)`;
}

function addMessage(username: string, message: string): void {
  const messages = document.getElementById('messages') as HTMLDivElement;
  const messageElement = document.createElement('div');

  const color = getUsernameColor(username);
  messageElement.innerHTML = `<strong style="color:${color}">${username}</strong><span style="color: #ffffff">:</span> ${message}`;
  messages.appendChild(messageElement);
  messages.scrollTop = messages.scrollHeight;
}

function updateUserList(users: string[]): void {
  const userList = document.getElementById('users') as HTMLUListElement;
  userList.innerHTML = '';
  users.forEach(user => {
    const li = document.createElement('li');
    const color = getUsernameColor(user);
    li.innerHTML = `<span style="color:${color}">${user}</span>`;
    userList.appendChild(li);
  });
}